package com.nomito.minimito.service.impl;

import com.alibaba.fastjson.JSON;
import com.nomito.minimito.common.constant.MsgActionEnum;
import com.nomito.minimito.common.constant.SearchFriendsStatusEnum;
import com.nomito.minimito.entity.ImRequestEntity;
import com.nomito.minimito.entity.ImUserEntity;
import com.nomito.minimito.netty.DataContent;
import com.nomito.minimito.netty.UserChanelRel;
import com.nomito.minimito.service.ImRequestService;
import com.nomito.minimito.service.ImUserService;
import com.nomito.minimito.vo.FriendRequestVo;
import com.nomito.minimito.vo.MyFriendsVO;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nomito.minimito.common.utils.PageUtils;
import com.nomito.minimito.common.utils.Query;

import com.nomito.minimito.dao.ImFriendDao;
import com.nomito.minimito.entity.ImFriendEntity;
import com.nomito.minimito.service.ImFriendService;
import org.springframework.transaction.annotation.Transactional;


@Service("imFriendService")
public class ImFriendServiceImpl extends ServiceImpl<ImFriendDao, ImFriendEntity> implements ImFriendService {

    @Autowired
    ImUserService userService;

    @Autowired
    ImRequestService friendRequestService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ImFriendEntity> page = this.page(
                new Query<ImFriendEntity>().getPage(params),
                new QueryWrapper<ImFriendEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public long getFriendCount(Long userId) {
        return baseMapper.selectCount(userId);
    }

    @Override
    public Integer preconditionSearchFriend(Long myUserId, String username) {
        //查询是否存在
        ImUserEntity userEntity = userService.getOne(new QueryWrapper<ImUserEntity>().select("id", "username", "nickname").eq("username", username));

        //1.搜索的用户如果不存在，则返回【无此用户】
        if(userEntity==null){
            return SearchFriendsStatusEnum.USER_NOT_EXIST.code;
        }
        //2.搜索的账号如果是你自己，则返回【不能添加自己】
        if(myUserId == userEntity.getId()){
            return SearchFriendsStatusEnum.NOT_YOURSELF.code;
        }
        //3.搜索的朋友已经是你好友，返回【该用户已经是你的好友】
        ImFriendEntity one = this.getOne(new QueryWrapper<ImFriendEntity>().eq("user_id", myUserId).eq("friend_id", userEntity.getId()));
//        MyFriends myF = t.selectOneByExample(friendEntity);
        if(one!=null){
            return SearchFriendsStatusEnum.ALREADY_FRIENDS.code;
        }
        return SearchFriendsStatusEnum.SUCCESS.code;
    }

    @Override
    public void passFriendRequest(Long sendUserId, Long acceptUserId) {
        //进行双向好友数据保存
        saveFriends(sendUserId,acceptUserId);
        saveFriends(acceptUserId,sendUserId);

        //删除好友请求表中的数据
        friendRequestService.remove(new QueryWrapper<ImRequestEntity>().eq("send_user_id",sendUserId).eq("accept_user_id",acceptUserId));

        Channel sendChannel  = UserChanelRel.get(sendUserId);
        if(sendChannel!=null){
            //使用websocket 主动推送消息到请求发起者，更新他的通讯录列表为最新
            DataContent dataContent = new DataContent();
            dataContent.setAction(MsgActionEnum.PULL_FRIEND.type);
            //消息的推送
            sendChannel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(dataContent)));
        }

    }

    @Override
    public List<MyFriendsVO> queryMyFriends(Long userId) {
        return baseMapper.queryMyFriends(userId);
    }

    @Override
    @Transactional
    public boolean deleteForTwoUser(Long myId, Long myfriendId) {
        boolean b = deleteFriends(myId, myfriendId);
        boolean b1 = deleteFriends(myId, myfriendId);
        return b&&b1;
    }

    private boolean deleteFriends(Long myId, Long myfriendId){
        return this.remove(new QueryWrapper<ImFriendEntity>().eq("user_id", myId).eq("friend_id", myfriendId));
    }
    private void saveFriends(Long sendUserId, Long acceptUserId){
        ImFriendEntity friendEntity = new ImFriendEntity();
        friendEntity.setUserId(acceptUserId);
        friendEntity.setFriendId(sendUserId);
        this.save(friendEntity);
    }


}